﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Windows.Controls;
using Microsoft.Windows.Controls.Primitives;

namespace ResourceBlender.Express {
    /// <summary>
    /// Methods specific to the WPF Toolkit DataGrid, these will probably be added to the core functionality in the future.
    /// </summary>
    public static class DataGridUtils {
        public static DataGridCell GetCell(DataGrid dataGrid, int row, int column) {
            DataGridRow rowContainer = GetRow(dataGrid, row);
            if(rowContainer != null) {
                DataGridCellsPresenter presenter = WPFUtils.GetVisualChild<DataGridCellsPresenter>(rowContainer);
                // try to get the cell but it may possibly be virtualized
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                if(cell == null) {
                    // now try to bring into view and retreive the cell
                    dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                }
                return cell;
            }
            return null;
        }

        public static DataGridRow GetRow(DataGrid dataGrid, int index) {
            DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
            if(row == null) {
                // may be virtualized, bring into view and try again
                dataGrid.ScrollIntoView(dataGrid.Items[index]);
                row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
            }
            return row;
        }
    }
}
